import requests
import json
import time

cookie = {}

with open("config.json") as fs:
    cookie = json.load(fs)

count = 1  # 有效总线索数
q = 1  # 当前查询接口次数

# 主逻辑


def main():
    global count
    url = "http://crm.jpushoa.com/api/web/clue/developerList/findByPage?page=1&pageSize=10&queryType=companyName&keyword=公司"
    res = requests.get(url, cookies=cookie)
    if res.status_code != 200:
        print("cookie invalid")
        return

    jsonData = json.loads(res.content)
    obj = jsonData["data"]["list"][0]
    if not obj["province"] in [
        "上海市",
        "江苏省",
        "浙江省",
        "安徽省",
    ]:

        print("not hit", q, "count：", count)
        return
    '''
    if count % 2 ==0:
        return
    if count > 100:
        return
    '''

    name = obj["companyName"]
    province = obj["province"]
    if province == "上海市":
        province = "上海"
    contact = obj["contact"]
    devId = obj["devId"]
    phoneid = getPhone(devId, province, obj["createTime"])

    # 用名称查询是否已创建
    if queryExists(name):
        print("%s exists skip" % name, "count：", count)
        return
    count = count + 1
    id, name = getCompanyId(name)
    obj = makeJson(name, id, province, contact, phoneid)

    ret = add(obj)
    print("count:", count)
    print("result:", ret)


# 用名称查询公司的id


def getCompanyId(name):
    res = requests.get(
        "https://crm.jpushoa.com/api/web/customer/company/getCompanyInfoList?keyword=%s"
        % name,
        cookies=cookie,
    )
    jsonData = json.loads(res.content)
    return jsonData["data"][0]["id"], jsonData["data"][0]["name"]


# 用devId查询完整手机号码


def getPhone(devId, province, createTime):
    res = requests.get(
        "https://crm.jpushoa.com/api/web/clue/developerList/viewContactMobile?devId=%s&province=%s&createTime=%s"
        % (devId, province, createTime),
        cookies=cookie,
    )
    jsonData = json.loads(res.content)
    return jsonData["data"]["mobile"]


# 新增


def add(obj):
    res = requests.post(
        "https://crm.jpushoa.com/api/web/customer/add",
        data=json.dumps(obj),
        cookies=cookie,
        headers={"Content-Type": "application/json;charset=UTF-8"},
    )
    print("new data:", obj["company"]["name"])
    return res.json()


# 查询公司名称是否存在


def queryExists(name):
    res = requests.get(
        "https://crm.jpushoa.com/api/web/customer/company/getCompanyList?page=1&pageSize=10&keyword=%s"
        % name,
        cookies=cookie,
    )
    jsonData = res.json()
    return len(jsonData["data"]["list"]) > 0


# 构建新增数据


def makeJson(name, srcId, province, salarName, phone):
    return {
        "company": {
            "name": name,
            "address": "",
            "type": 2,
            "companySourceId": srcId,
            "province": province,
            "city": "",
            "district": "",
            "latLong": "",
            "grade": 0,
        },
        "customer": {
            "opName": "push推送",
            "businessId": 1,
            "areaId": 1,
            "salerId": 3580,
            "customerContacts": [
                {"name": salarName, "position": "对接人", "phone": phone, "leaderFlag": 0}
            ],
            "devinfos": [],
        },
    }


while count < 100:
    try:
        main()
    except Exception as err:
        print("出现问题了，可能掉线了 也可能是其它问题")
        print(err)
    q = q + 1
    time.sleep(1)
